package com.iamteer.metadata;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

import org.junit.Test;

public class App {
	private Connection con;
	
	private String url = "jdbc:mysql:///day18"; 
	private String user = "root"; 
	private String password = "123456"; 
	
	//1. 数据库元数据
	@Test
	public void testDB() throws Exception {
		//连接数据库
		Class.forName("com.mysql.jdbc.Driver");
		con = DriverManager.getConnection(url, user, password);
		
		//获取数据库元数据
		DatabaseMetaData metaData = con.getMetaData();
		
		System.out.println(metaData.getUserName());
		System.out.println(metaData.getURL());
		System.out.println(metaData.getDriverName());
		System.out.println(metaData.getDatabaseProductName());
	}
	
	// 2. 参数元数据
	@Test
	public void testParams() throws Exception{
		//连接数据库
		Class.forName("com.mysql.jdbc.Driver");
		con = DriverManager.getConnection(url, user, password);
		
		String sql = "select * from dept where deptid=? and deptName=?";
		
		PreparedStatement pstmt = con.prepareStatement(sql);
		// 参数元数据
		ParameterMetaData p_MetaData = pstmt.getParameterMetaData();
		// 获取参数元数据个数
		int count = p_MetaData.getParameterCount();
		System.out.println(count);
	}
	
	// 3. 结果集元数据
	@Test
	public void testRs() throws Exception{
		//连接数据库
		Class.forName("com.mysql.jdbc.Driver");
		con = DriverManager.getConnection(url, user, password);
		
		String sql = "select * from dept";
		
		PreparedStatement pstmt = con.prepareStatement(sql);
		ResultSet rs = pstmt.executeQuery();
		
		// 结果集元数据
		ResultSetMetaData rs_metaData = rs.getMetaData();
		
		while (rs.next()) {
			// 1. 获取参数元数据个数
			int count = rs_metaData.getColumnCount();
			for (int i = 0; i < count; i++) {
				// 得到列的名称
				String columnName = rs_metaData.getColumnName(i + 1);
				// 获取每一行的每一列的值
				Object columnValue = rs.getObject(columnName);
				System.out.print(columnName + "=" + columnValue + ", ");
			}
			System.out.println();
		}
	}
}
